document.addEventListener('DOMContentLoaded', () => {
    const apiKeyInput = document.getElementById('apiKey');
    const modelNameInput = document.getElementById('modelName');
    const userInput = document.getElementById('userInput');
    const sendBtn = document.getElementById('sendBtn');
    const chatWindow = document.getElementById('chatWindow');
    const statusMessage = document.getElementById('statusMessage');
    const newChatBtn = document.getElementById('newChatBtn');
    const chatHistoryList = document.getElementById('chatHistoryList');
    const settingsToggle = document.getElementById('settingsToggle');
    const settingsPanel = document.getElementById('settingsPanel');
    const saveSettingsBtn = document.getElementById('saveSettingsBtn');
    
    // 新增元素
    const attachBtn = document.getElementById('attachBtn');
    const fileInput = document.getElementById('fileInput');
    const filePreview = document.getElementById('filePreview');

    let currentConversation = [];
    let messageIdCounter = 0;
    let isMobile = window.innerWidth <= 768;
    let isResizing = false;
    let attachedFiles = []; // 存储附件信息

    const MAX_MESSAGES_TO_SAVE = 100;
    const MAX_FILE_SIZE = 20 * 1024 * 1024; // 20MB
    const ALLOWED_FILE_TYPES = [
        'image/jpeg', 'image/png', 'image/gif', 'image/webp'
    ];

    // ===== 响应式处理函数 =====
    
    // 检测设备类型
    function detectDeviceType() {
        const wasMobile = isMobile;
        isMobile = window.innerWidth <= 768;
        
        // 如果设备类型发生变化，重新调整布局
        if (wasMobile !== isMobile) {
            handleLayoutChange();
        }
    }
    
    // 处理布局变化
    function handleLayoutChange() {
        // 在移动端自动隐藏设置面板
        if (isMobile && !settingsPanel.classList.contains('hidden')) {
            settingsPanel.classList.add('hidden');
            settingsToggle.setAttribute('aria-expanded', 'false');
        }
        
        // 调整输入框高度
        adjustTextareaHeight();
        
        // 重新计算滚动位置
        setTimeout(() => {
            chatWindow.scrollTop = chatWindow.scrollHeight;
        }, 100);
    }
    
    // 调整文本框高度
    function adjustTextareaHeight() {
        userInput.style.height = 'auto';
        const scrollHeight = userInput.scrollHeight;
        const maxHeight = isMobile ? 120 : 150; // 移动端限制最大高度
        userInput.style.height = Math.min(scrollHeight, maxHeight) + 'px';
    }
    
    // 防抖函数
    function debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }
    
    // 窗口大小变化处理
    const handleResize = debounce(() => {
        if (!isResizing) {
            isResizing = true;
            detectDeviceType();
            setTimeout(() => {
                isResizing = false;
            }, 100);
        }
    }, 250);
    
    // 监听窗口大小变化
    window.addEventListener('resize', handleResize);
    
    // 监听设备方向变化
    window.addEventListener('orientationchange', () => {
        setTimeout(() => {
            detectDeviceType();
        }, 100);
    });

    // ===== 移动端优化 =====
    
    // 防止iOS缩放
    function preventZoom() {
        let lastTouchEnd = 0;
        document.addEventListener('touchend', function (event) {
            const now = (new Date()).getTime();
            if (now - lastTouchEnd <= 300) {
                event.preventDefault();
            }
            lastTouchEnd = now;
        }, false);
    }
    
    // 触摸事件优化
    function setupTouchEvents() {
        // 为可点击元素添加触摸反馈
        const touchElements = document.querySelectorAll('.chat-history-item, .settings-toggle, .new-chat-btn, .save-settings-btn, #sendBtn');
        
        touchElements.forEach(element => {
            element.addEventListener('touchstart', function() {
                this.style.opacity = '0.7';
            });
            
            element.addEventListener('touchend', function() {
                this.style.opacity = '1';
            });
        });
    }
    
    // 键盘导航支持
    function setupKeyboardNavigation() {
        // 设置面板的键盘导航
        settingsToggle.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                settingsToggle.click();
            }
        });
        
        // 聊天历史项的键盘导航
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                // ESC键关闭设置面板
                if (!settingsPanel.classList.contains('hidden')) {
                    settingsPanel.classList.add('hidden');
                    settingsToggle.setAttribute('aria-expanded', 'false');
                }
            }
        });
    }

    // ===== 初始化响应式功能 =====
    detectDeviceType();
    preventZoom();
    setupTouchEvents();
    setupKeyboardNavigation();

    // ===== 文件处理函数 =====
    
    // 格式化文件大小
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
    
    // 获取文件图标
    function getFileIcon(fileType) {
        if (fileType.startsWith('image/')) return '🖼️';
        if (fileType === 'application/pdf') return '📄';
        if (fileType === 'text/plain') return '📝';
        if (fileType.includes('word')) return '📘';
        if (fileType.includes('excel') || fileType.includes('spreadsheet')) return '📊';
        if (fileType.includes('powerpoint') || fileType.includes('presentation')) return '📽️';
        return '📎';
    }
    
    // 验证文件
    function validateFile(file) {
        if (file.size > MAX_FILE_SIZE) {
            showStatus(`文件 ${file.name} 太大，最大支持 20MB`, "error");
            return false;
        }
        
        if (!ALLOWED_FILE_TYPES.includes(file.type)) {
            showStatus(`不支持的文件类型: ${file.type}。只支持图片格式 (PNG, JPG, GIF, WebP)`, "error");
            return false;
        }
        
        // 额外检查文件扩展名
        const fileName = file.name.toLowerCase();
        const allowedExtensions = ['.png', '.jpg', '.jpeg', '.gif', '.webp'];
        const hasValidExtension = allowedExtensions.some(ext => fileName.endsWith(ext));
        
        if (!hasValidExtension) {
            showStatus(`文件 ${file.name} 格式不支持。只支持图片格式 (PNG, JPG, GIF, WebP)`, "error");
            return false;
        }
        
        return true;
    }
    
    // 处理文件选择
    function handleFileSelect(files) {
        Array.from(files).forEach(file => {
            if (validateFile(file)) {
                addFileToPreview(file);
            }
        });
    }
    
    // 添加文件到预览
    function addFileToPreview(file) {
        const fileId = Date.now() + Math.random();
        const fileInfo = {
            id: fileId,
            file: file,
            name: file.name,
            size: file.size,
            type: file.type
        };
        
        attachedFiles.push(fileInfo);
        renderFilePreview();
    }
    
    // 渲染文件预览
    function renderFilePreview() {
        if (attachedFiles.length === 0) {
            filePreview.classList.remove('show');
            return;
        }
        
        filePreview.classList.add('show');
        filePreview.innerHTML = '';
        
        attachedFiles.forEach(fileInfo => {
            const fileItem = document.createElement('div');
            fileItem.className = 'file-item';
            fileItem.innerHTML = `
                <div class="file-icon">${getFileIcon(fileInfo.type)}</div>
                <div class="file-info">
                    <div class="file-name">${fileInfo.name}</div>
                    <div class="file-size">${formatFileSize(fileInfo.size)}</div>
                </div>
                <button class="file-remove" onclick="removeFile('${fileInfo.id}')" aria-label="移除文件">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <line x1="18" y1="6" x2="6" y2="18"></line>
                        <line x1="6" y1="6" x2="18" y2="18"></line>
                    </svg>
                </button>
            `;
            
            // 如果是图片，添加预览
            if (fileInfo.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const img = document.createElement('img');
                    img.src = e.target.result;
                    img.className = 'image-preview';
                    img.alt = fileInfo.name;
                    fileItem.appendChild(img);
                };
                reader.readAsDataURL(fileInfo.file);
            }
            
            filePreview.appendChild(fileItem);
        });
    }
    
    // 移除文件
    function removeFile(fileId) {
        attachedFiles = attachedFiles.filter(f => f.id !== fileId);
        renderFilePreview();
    }
    
    // 清空所有附件
    function clearAttachments() {
        attachedFiles = [];
        renderFilePreview();
    }
    
    // 将移除文件函数设为全局，以便在HTML中调用
    window.removeFile = removeFile;

    // --- loadScript 函数 (保持不变，已包含调试日志) ---
    function loadScript(id, url) {
        return new Promise((resolve, reject) => {
            const script = document.getElementById(id);
            let globalVarName;
            if (id === 'markedJs') {
                globalVarName = 'marked';
            } else if (id === 'highlightJs') {
                globalVarName = 'hljs';
            } else {
                globalVarName = id.replace('Js', '');
            }

            if (script && typeof window[globalVarName] !== 'undefined') {

                resolve();
                return;
            }

            if (script) {
                script.onload = () => {
                    resolve();
                };
                script.onerror = (e) => {
                    reject(e);
                };
            } else {
                // Should not happen as script tags are in HTML
                const newScript = document.createElement('script');
                newScript.id = id;
                newScript.src = url;
                newScript.onload = () => {
                    resolve();
                };
                newScript.onerror = (e) => {
                    reject(e);
                };
                document.head.appendChild(newScript);
            }
        });
    }

    // --- setupMarkdownAndHighlighting 函数 ---
    function setupMarkdownAndHighlighting() {
        if (typeof marked === 'undefined' || typeof hljs === 'undefined') {
            return;
        }

        // **核心修改 Marked.js 选项**
        marked.setOptions({
            // renderer: new marked.Renderer(), // 可以自定义渲染器，但现在不必要
            gfm: true, // 启用 GitHub Flavored Markdown
            breaks: true, // 启用换行符转换为 <br>
            // 如果上述两项仍不行，可以尝试更严格的段落处理
            // 如果marked.js版本很新，可能需要 marked.use() 而不是 setOptions
            // Marked.js V5+ 版本推荐使用 marked.use()，而不是 marked.setOptions()
            // 如果你的marked.js是V5或更高版本，请考虑更新为 marked.use()
            // marked.use({ breaks: true, gfm: true, highlight: ... });
            highlight: function(code, lang) {
                const language = hljs.getLanguage(lang) ? lang : 'plaintext';
                return hljs.highlight(code, { language }).value;
            },
            langPrefix: 'hljs language-',
        });
    }


    function initializeChat() {
        // **确保 Marked 和 Highlight.js 已经配置好**
        // 这行代码必须在任何调用 appendMessage 之前执行，
        // 并且 Promise.all 已经保证了 marked 和 hljs 的全局对象存在。
        if (typeof marked !== 'undefined' && typeof hljs !== 'undefined') {
            setupMarkdownAndHighlighting();
        } else {
            // 可以在这里显示一个错误消息给用户
            showStatus("核心渲染库加载失败，历史消息可能无法正常显示。", "error", 5000);
        }

        apiKeyInput.value = localStorage.getItem('geminiApiKey') || '';
        modelNameInput.value = localStorage.getItem('geminiModelName') || 'gemini-1.5-pro-latest';
        
        const savedConversation = localStorage.getItem('geminiChatConversation');

        if (savedConversation) {
            try {
                const parsedConversation = JSON.parse(savedConversation);
                if (Array.isArray(parsedConversation) && parsedConversation.length > 0) {
                    currentConversation = parsedConversation;
                    chatWindow.innerHTML = '';
                    chatHistoryList.innerHTML = '';
                    messageIdCounter = 0;

                    currentConversation.forEach((msg, index) => {
                        const newId = `message-${messageIdCounter++}`;
                        msg.id = newId;

                        // **关键：调用 appendMessage 渲染历史消息**
                        // isStreamingPlaceholder 设为 false，因为是完整的历史消息
                        // shouldScroll 设为 false，最后统一滚动
                        appendMessage(msg.content, msg.role, msg.id, false, false);
                        
                        if (msg.role === 'user') {
                            addHistoryItem(msg.content, msg.id);
                        }
                    });

                    chatWindow.scrollTop = chatWindow.scrollHeight;
                    
                    if (typeof hljs !== 'undefined') {
                        chatWindow.querySelectorAll('pre code').forEach((block) => {
                            hljs.highlightElement(block);
                        });
                    } else {
                    }

                    showStatus("已加载历史会话。", "info", 1500);
                } else {
                    newChat(false);
                }
            } catch (e) {
                showStatus("加载历史会话失败，已开始新会话。", "error", 3000);
                newChat(false);
            }
        } else {
            newChat(false);
        }

        // 使用响应式函数调整文本框高度
        adjustTextareaHeight();
    }

    function saveConversation() {
        let conversationToSave = [...currentConversation];
        if (conversationToSave.length > MAX_MESSAGES_TO_SAVE) {
            conversationToSave = conversationToSave.slice(conversationToSave.length - MAX_MESSAGES_TO_SAVE);
        }
        const jsonString = JSON.stringify(conversationToSave);
        localStorage.setItem('geminiChatConversation', jsonString);
    }

    // --- 事件监听器 (更新为响应式版本) ---
    sendBtn.addEventListener('click', sendMessage);
    
    // 键盘事件处理
    userInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    });
    
    // 输入框高度自适应
    userInput.addEventListener('input', () => {
        adjustTextareaHeight();
    });
    
    // 新建聊天
    newChatBtn.addEventListener('click', () => newChat(true));
    
    // 设置面板切换
    settingsToggle.addEventListener('click', () => {
        const isHidden = settingsPanel.classList.contains('hidden');
        settingsPanel.classList.toggle('hidden');
        settingsToggle.setAttribute('aria-expanded', !isHidden);
        
        // 移动端自动聚焦到API Key输入框
        if (!isHidden && isMobile) {
            setTimeout(() => {
                apiKeyInput.focus();
            }, 100);
        }
    });
    
    // 保存设置
    saveSettingsBtn.addEventListener('click', () => {
        localStorage.setItem('geminiApiKey', apiKeyInput.value.trim());
        localStorage.setItem('geminiModelName', modelNameInput.value.trim());
        showStatus("设置已保存！", "success");
        settingsPanel.classList.add('hidden');
        settingsToggle.setAttribute('aria-expanded', 'false');
        
        // 移动端保存后自动聚焦到输入框
        if (isMobile) {
            setTimeout(() => {
                userInput.focus();
            }, 100);
        }
    });
    
    // 文件上传相关事件
    attachBtn.addEventListener('click', () => {
        fileInput.click();
    });
    
    fileInput.addEventListener('change', (e) => {
        if (e.target.files.length > 0) {
            handleFileSelect(e.target.files);
            e.target.value = ''; // 清空input，允许重复选择同一文件
        }
    });
    
    // 聊天历史项点击事件
    chatHistoryList.addEventListener('click', (e) => {
        const historyItem = e.target.closest('.chat-history-item');
        if (historyItem) {
            e.preventDefault();
            const chatId = historyItem.getAttribute('data-chat-id');
            if (chatId) {
                scrollToMessage(chatId);
                setActiveHistoryItem(historyItem);
            }
        }
    });
    
    // 聊天历史项键盘导航
    chatHistoryList.addEventListener('keydown', (e) => {
        if (e.key === 'Enter' || e.key === ' ') {
            const historyItem = e.target.closest('.chat-history-item');
            if (historyItem) {
                e.preventDefault();
                historyItem.click();
            }
        }
    });
    
    // 移动端输入框聚焦优化
    userInput.addEventListener('focus', () => {
        if (isMobile) {
            // 移动端聚焦时确保输入框可见
            setTimeout(() => {
                userInput.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }, 300);
        }
    });
    
    // 防止移动端双击缩放
    userInput.addEventListener('dblclick', (e) => {
        if (isMobile) {
            e.preventDefault();
        }
    });

    // --- 配置 marked.js (保持不变) ---
    marked.setOptions({
        highlight: function(code, lang) {
            const language = hljs.getLanguage(lang) ? lang : 'plaintext';
            return hljs.highlight(code, { language }).value;
        },
        langPrefix: 'hljs language-',
        breaks: true,
        gfm: true,
    });

    // --- 核心消息发送逻辑 (更新为支持附件和联网搜索) ---
    async function sendMessage() {
        const apiKey = apiKeyInput.value.trim();
        const modelName = modelNameInput.value.trim();
        const messageText = userInput.value.trim();

        if (!apiKey) {
            showStatus("请输入 Gemini API Key。", "error");
            return;
        }
        if (!modelName) {
            showStatus("请输入模型名称。", "error");
            return;
        }
        if (!messageText && attachedFiles.length === 0) {
            return;
        }

        const userMessageId = `message-${messageIdCounter++}`;
        currentConversation.push({ role: 'user', content: messageText, id: userMessageId });
        appendMessage(messageText, 'user', userMessageId);
        addHistoryItem(messageText, userMessageId);

        userInput.value = '';
        adjustTextareaHeight();
        showStatus("AI 正在思考中...", "info");
        sendBtn.disabled = true;

        try {
            const messagesToSend = currentConversation.map(msg => ({ role: msg.role, content: msg.content }));
            const conversationHistoryLimit = 20;
            if (messagesToSend.length > conversationHistoryLimit) {
                messagesToSend.splice(0, messagesToSend.length - conversationHistoryLimit);
            }

            // 准备请求数据
            const requestData = {
                model: modelName,
                messages: messagesToSend,
                stream: true
            };

            // 如果有附件，先上传文件并添加到消息中
            if (attachedFiles.length > 0) {
                showStatus("正在上传附件...", "info");
                const uploadedFiles = await uploadFiles(attachedFiles);
                if (uploadedFiles.length > 0) {
                    // 将文件信息添加到最后一条用户消息中
                    const lastMessage = messagesToSend[messagesToSend.length - 1];
                    if (lastMessage && lastMessage.role === 'user') {
                        const content = [];
                        
                        // 添加文本内容
                        if (lastMessage.content && lastMessage.content.trim()) {
                            content.push({
                                type: "text",
                                text: lastMessage.content
                            });
                        }
                        
                        // 添加文件内容
                        uploadedFiles.forEach(file => {
                            content.push({
                                type: "image_url",
                                image_url: {
                                    url: file.url
                                }
                            });
                        });
                        
                        lastMessage.content = content;
                    }
                }
            }

            const response = await fetch('/v1/chat/completions', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Gemini-Api-Key': apiKey
                },
                body: JSON.stringify(requestData)
            });

            if (!response.ok) {
                const errorData = await response.json().catch(() => ({ message: response.statusText }));
                throw new Error(`API 请求失败: ${errorData.message || response.status} - ${JSON.stringify(errorData)}`);
            }

            const reader = response.body.getReader();
            const decoder = new TextDecoder('utf-8');
            let receivedText = '';
            
            const aiMessageId = `message-${messageIdCounter++}`;
            appendMessage('', 'bot', aiMessageId, true); // 流式占位符
            const botMessageElement = document.getElementById(aiMessageId).querySelector('.message-text');

            while (true) {
                const { done, value } = await reader.read();
                if (done) {
                    break;
                }
                const chunk = decoder.decode(value, { stream: true });
                const lines = chunk.split('\n');
                for (const line of lines) {
                    if (line.startsWith('data: ')) {
                        const jsonStr = line.substring(6);
                        if (jsonStr === '[DONE]') {
                            break;
                        }
                        try {
                            const data = JSON.parse(jsonStr);
                            const deltaContent = data.choices[0]?.delta?.content || '';
                            receivedText += deltaContent;

                            botMessageElement.innerHTML = marked.parse(receivedText);
                            botMessageElement.querySelectorAll('pre code').forEach((block) => {
                                hljs.highlightElement(block);
                            });
                            chatWindow.scrollTop = chatWindow.scrollHeight;
                        } catch (parseError) {
                            console.error('Error parsing stream chunk:', parseError, jsonStr);
                        }
                    }
                }
            }
            // 流结束后，将最终的 AI 响应添加到 currentConversation 并保存
            currentConversation.push({ role: 'assistant', content: receivedText, id: aiMessageId });
            saveConversation(); // 保存会话

            // 清空附件
            clearAttachments();

            showStatus("消息已发送。", "success");

        } catch (error) {
            showStatus(`聊天请求出错: ${error.message}`, "error");
        } finally {
            chatWindow.scrollTop = chatWindow.scrollHeight;
            sendBtn.disabled = false;
        }
    }

    // 文件上传函数
    async function uploadFiles(files) {
        const uploadedFiles = [];
        
        for (const fileInfo of files) {
            try {
                const formData = new FormData();
                formData.append('file', fileInfo.file);
                
                const response = await fetch('/v1/upload', {
                    method: 'POST',
                    body: formData
                });
                
                if (response.ok) {
                    const result = await response.json();
                    uploadedFiles.push({
                        name: fileInfo.name,
                        type: fileInfo.type,
                        url: result.url,
                        id: result.file_id
                    });
                } else {
                    showStatus(`文件 ${fileInfo.name} 上传失败`, "error");
                }
            } catch (error) {
                showStatus(`文件 ${fileInfo.name} 上传出错: ${error.message}`, "error");
            }
        }
        
        return uploadedFiles;
    }

    // --- 消息添加到 DOM 的函数 (appendMessage) ---
    function appendMessage(text, sender, id, isStreamingPlaceholder = false, shouldScroll = true) {
        const messageWrapper = document.createElement('div');
        messageWrapper.classList.add('message-wrapper', sender); // sender (user/bot) 用于CSS类
        if (id) {
            messageWrapper.id = id;
        }

        const avatarDiv = document.createElement('div');
        avatarDiv.classList.add('message-avatar');
        // 根据 sender 参数来确定头像和消息类型
        avatarDiv.textContent = (sender === 'user') ? '👤' : '🤖'; 

        const contentDiv = document.createElement('div');
        contentDiv.classList.add('message-content');

        const textDiv = document.createElement('div');
        textDiv.classList.add('message-text');

        // **核心修改：判断 sender 是否为 AI 角色**
        // 确保 `sender` 为 'bot' 或 'assistant' 时，都进行 Markdown 渲染
        if (sender === 'bot' || sender === 'assistant') { // <--- 关键修改这里
            if (typeof marked !== 'undefined' && typeof marked.parse === 'function') {
                try {
                    let preprocessedText = text.replace(/(?<!\n)\n(?!\n)/g, '  \n'); 
                    const parsedHtml = marked.parse(preprocessedText);
                    textDiv.innerHTML = parsedHtml;
                    
                } catch (parseError) {
                    textDiv.textContent = text;
                }
            } else {
                textDiv.textContent = text;

            }
        } else { // sender is 'user' or any other unexpected role
            textDiv.textContent = text;

        }

        contentDiv.appendChild(textDiv);
        messageWrapper.appendChild(avatarDiv);
        messageWrapper.appendChild(contentDiv);

        chatWindow.appendChild(messageWrapper);

        if (shouldScroll) {
            chatWindow.scrollTop = chatWindow.scrollHeight;
        }
    }


    // --- 添加历史条目到左侧栏的函数 (保持不变) ---
    function addHistoryItem(userMessage, messageId) {
        const historyItem = document.createElement('a');
        historyItem.href = `#${messageId}`;
        historyItem.classList.add('chat-history-item');
        historyItem.setAttribute('data-chat-id', messageId);

        const iconSvg = `
            <svg stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" class="h-4 w-4" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V3a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path></svg>
        `;
        const titleSpan = document.createElement('span');
        titleSpan.textContent = userMessage.substring(0, 15) + (userMessage.length > 15 ? '...' : '');

        historyItem.innerHTML = iconSvg;
        historyItem.appendChild(titleSpan);

        historyItem.addEventListener('click', (e) => {
            e.preventDefault();
            const targetId = historyItem.getAttribute('data-chat-id');
            scrollToMessage(targetId);
            setActiveHistoryItem(historyItem);
        });

        setActiveHistoryItem(historyItem);
        chatHistoryList.appendChild(historyItem);
    }

    // --- 设置激活状态的函数 (保持不变) ---
    function setActiveHistoryItem(activeItem) {
        const allItems = chatHistoryList.querySelectorAll('.chat-history-item');
        allItems.forEach(item => item.classList.remove('active'));
        activeItem.classList.add('active');
    }

    // --- 滚动到指定消息的函数 (修复拼写错误) ---
    function scrollToMessage(messageId) {
        const messageElement = document.getElementById(messageId);
        if (messageElement) {
            messageElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
    }

    // --- 新建会话函数 (更新为清空附件) ---
    function newChat(showStatusMsg = true) {
        currentConversation = [];
        messageIdCounter = 0;
        clearAttachments(); // 清空附件
        
        chatWindow.innerHTML = `
            <div class="message-wrapper system" id="initial-welcome-message">
                <div class="message-avatar">🤖</div>
                <div class="message-content">
                    <div class="message-text">你好！请在左侧点击"设置"按钮输入你的 Gemini API Key 和模型名称，然后开始聊天吧。你可以上传图片、PDF等文件进行多模态对话。</div>
                </div>
            </div>
        `;
        chatHistoryList.innerHTML = `
            <a href="#" class="chat-history-item active" data-chat-id="initial-welcome-message">
                <svg stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" class="h-4 w-4" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V3a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path></svg>
                <span>欢迎</span>
            </a>
        `;
        userInput.value = '';
        userInput.style.height = 'auto';
        if (showStatusMsg) {
            showStatus("已开始新会话。", "info");
        }
        scrollToMessage('initial-welcome-message');
        saveConversation();
    }

    // --- 显示状态消息的函数 (保持不变) ---
    function showStatus(message, type, duration = 3000) {
        statusMessage.textContent = message;
        statusMessage.className = 'status-message';
        if (type) {
            statusMessage.classList.add(type);
        }
        statusMessage.style.display = 'block';
        setTimeout(() => {
            statusMessage.style.display = 'none';
        }, duration);
    }

    // --- 页面加载完成时执行初始化 (保持不变) ---
    Promise.all([
        //loadScript('markedJs', 'https://cdn.jsdelivr.net/npm/marked/marked.min.js'),
        loadScript('highlightJs', 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js')
    ])
    .then(() => {
        setupMarkdownAndHighlighting();
        initializeChat();
    })
    .catch(error => {
        showStatus("加载聊天功能失败，请检查网络。", "error", 5000);
        initializeChat();
    });

});